﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Othello
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        }

        private Board board = new Board();
        private Rectangle[,] squares = new Rectangle[Board.Size, Board.Size];
        private Color selfColor = Colors.White, otherColor = Colors.Black;

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < Board.Size; i++)
            {
                for (int j = 0; j < Board.Size; j++)
                {
                    Rectangle rect = new Rectangle() { Width = 40, Height = 40 };
                    rect.SetValue(Canvas.LeftProperty, i * 42d);
                    rect.SetValue(Canvas.TopProperty, j * 42d);
                    rect.Fill = new SolidColorBrush(GetColorOfPiece(board.GetPoint(i, j)));
                    squares[i, j] = rect;
                    canvasBorder.Children.Add(rect);
                }
            }
        }


        public void Redraw()
        {
            for (int i = 0; i < Board.Size; i++)
            {
                for (int j = 0; j < Board.Size; j++)
                {
                    squares[i, j].Fill = new SolidColorBrush(GetColorOfPiece(board.GetPoint(i, j)));
                }
            }
        }

        private Color GetColorOfPiece(Piece piece)
        {
            switch (piece)
            {
                case Piece.Moveable: return Colors.Yellow;
                case Piece.Self: return selfColor;
                case Piece.Other: return otherColor;
                default: return Colors.LightGray;
            }
        }

        private void canvasBorder_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
        }

        private void canvasBorder_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(canvasBorder);
            int i = (int)p.X / 42, j = (int)p.Y / 42;
            if (board.GetPoint(i,j) == Piece.Moveable)
            {
                board.PutDown(i, j);
                board.Reverse();
                Color tmp = selfColor;
                selfColor = otherColor;
                otherColor = tmp;
                Redraw();
            }
        }

        private void buttonReset_Click(object sender, RoutedEventArgs e)
        {
            board.Initlize();
            selfColor = Colors.White;
            otherColor = Colors.Black;
            Redraw();
        }
    }
}